package com.news.servlet.filter;

import com.news.bean.Constant;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by lingzhiyuan.
 * Date : 15/10/12.
 * Time : 下午2:14.
 * Description:
 *
 * 检查用户访问目标页面前是否已登录
 *
 */
public class LoginFilter implements Filter{

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest httpServletRequest = (HttpServletRequest)request;
        HttpServletResponse httpServletResponse = (HttpServletResponse)response;
        String path = httpServletRequest.getServletPath();

        boolean is_login = false;
        String username = null;
        int status = 0;

        if (Constant.LOGIN_FALLBACK_PAGE_URL.equals(path) || Constant.CHECK_LOGIN_PAGE_URL.equals(path)){
            chain.doFilter(request,response);
        }else {

            Cookie[] cookies = httpServletRequest.getCookies();
            if (cookies != null && cookies.length != 0){
                for (Cookie cookie : cookies){
                    if (cookie.getName().equals(Constant.Login_User_Cookie_Status_Name)){
                        status = Integer.parseInt(cookie.getValue());
                    }else {
                        if (cookie.getName().equals(Constant.Login_User_Cookie_Username_Name)){
                            username = cookie.getValue();
                        }
                    }
                }
            }

            if (username != null && status == Constant.USER_LOGIN_STATUS_ACTIVE){
                is_login = true;
            }

            if(is_login){
                chain.doFilter(request,response);
            }else {
                httpServletResponse.sendRedirect(Constant.LOGIN_FALLBACK_PAGE_URL);
            }

        }
    }

    @Override
    public void destroy() {

    }
}
